<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class OperationLog extends Model
{
    use HasFactory;

    protected $table = 'operation_logs';

    protected $fillable = [
        'user_id',
        'username',
        'method',
        'action',
        'resource',
        'resource_id',
        'description',
        'path',
        'params',
        'before_data',
        'after_data',
        'changes',
        'ip',
        'user_agent',
        'status',
        'message',
    ];

    protected $casts = [
        'params' => 'array',
        'before_data' => 'array',
        'after_data' => 'array',
        'changes' => 'array',
        'created_at' => 'datetime',
    ];
    
    // 只启用 created_at，禁用 updated_at（操作日志不需要更新时间）
    const UPDATED_AT = null;
    
    // 启用 created_at
    public $timestamps = true;

    /**
     * 序列化日期时间
     * 统一使用 Y-m-d H:i:s 格式，并转换为应用时区
     *
     * @param \DateTimeInterface $date
     * @return string
     */
    protected function serializeDate(\DateTimeInterface $date): string
    {
        $timezone = config('app.timezone', 'Asia/Shanghai');
        return \Carbon\Carbon::instance($date)
            ->setTimezone($timezone)
            ->format('Y-m-d H:i:s');
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

